#!/bin/bash
#查看远程服务器启动日志脚本
#将该脚本上传到tomcat的bin目录下   java中使用ssh直接调用终端脚本
# ssh ${host} "cd ${tomcatPath};./ox_release_tomcat_restart_log.sh ${logPath};"
#远程tail不能关闭远程终端机tail进程
#将tail命令脚本放置在远程终端机器上，服务器ssh远程执行脚本，
#java线程结束时，ssh kill 远程机的tail进程
#
#传入参数：日志路径
logPath=$1

#tail日志总条数,达到后自动关闭进程
totalCount=2000
#300s后自动关闭
totalTime=300


#拼接10条日志返回
count=10
#日志返回值
logStr=""
#开始时间
start=$(date "+%s")
echoStart=$(date "+%s")

#拼接返回字符串
buffer_str(){
    now=$(date "+%s")
    time=$((now-echoStart))
    logStr="$logStr<br>$1"
    if [ ${time} -ge 5 -o ${count} = 0 ]
    then
        echo ${logStr}
        echoStart=$(date "+%s")
        logStr=""
        count=10
    fi
}

#停止当前进程  $line
kill_tail(){
    now=$(date "+%s")
    time=$((now-start))

    if [ ${time} -ge `expr ${totalTime}` -o `expr ${totalCount}` = 0 ]
    then
        echo ${logStr}
        logStr=""
        process=`ps -ef | grep "tail -fn151 ${logPath}" | grep -v grep | awk '{print $2}'`
        if [ ${#process[*]} -ne 0 ];then
            for i in ${process[*]}
            do
                eval "kill -9 ${i}"
            done
        fi
        exit 0
    fi
}

{
    tail -fn151 ${logPath} | while read line
    do
        totalCount=`expr ${totalCount} - 1`
        count=`expr ${count} - 1`
        buffer_str "$line"
        #kill_tail
    done

}&

{
    while [ true ]
    do
        kill_tail
        sleep 1
    done
}&

wait
exit 0